<?php

namespace app\controller;

use support\Request;
use app\model\Admin;

class Index
{
    public function index(Request $request)
    {
        return view('login/index');
    }

    public function login(Request $request)
    {
        $username = $request->post('username');
        $password = $request->post('password');

        if($username==null || $password==null){
            return return_json(0, '用户名和密码不能为空');
        }

        /******************** 需要数据库验证时 ********************/
        /** 如不需要数据验证 删除此段代码 重构下面的 $temp 数组。$temp必须 **/
        $modelAdmin = new Admin;
        $where['username'] = $username;
        $where['status'] = 1;
        $infoAdmin = $modelAdmin->where($where)->find();
        if (empty($infoAdmin)) {
            return return_json(0, '用户名不存在');
        }

        $new_password = get_salt_password($password.$infoAdmin['id'],$infoAdmin['salt']);
        if ($infoAdmin['password'] != $new_password) {
            return return_json(0, '密码错误');
        }
        /******************** 需要数据库验证时 ********************/

        $token = md5(rand(100000, 999999) . time());
        $temp = array(
            'id' => $infoAdmin['id'],
            'username' => $infoAdmin['username'],
            'nickname' => $infoAdmin['nickname'],
            'token' => $token,
            'logintime' => time()
        );

        //添加session
        $session = $request->session();
        $session->put($temp);

        $temp['url'] = url('home/index');
        return return_json(1, '登录成功', $temp);
    }

    /**
     * 退出登录
     */
    public function logout(Request $request){
        $request->session()->flush();

        return return_json(2,'退出系统成功！',url('index/index'));
    }

}
